﻿using FreeDream.Model;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace FreeDream.WebApi.Filter
{
    /// <summary>
    /// 模型校验过滤器
    /// </summary>
    public class ModelValidateActionFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 参数验证过滤器
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                //获取验证失败的模型字段
                var errors = context.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();
                var str = string.Join("|", errors);
                //设置返回内容
                var result = new BaseResponse
                {
                    code = ResponseCode.PARAMERROR,
                    Message = "参数验证失败." + str,
                    timespan = DateTime.Now
                };
                context.Result = new BadRequestObjectResult(result);
            }
        }
    }
}
